{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "x_new: [1.85407557]\n",
      "目标值: -3.415577\n",
      "预测值: 5.381685\n",
      "预测值与真实值的绝对误差: [8.79726225]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "\n",
    "tf.compat.v1.disable_eager_execution()\n",
    "\n",
    "sess = tf.compat.v1.Session()\n",
    "x = tf.compat.v1.placeholder(dtype=tf.float32)\n",
    "y = tf.compat.v1.placeholder(dtype=tf.float32)\n",
    "\n",
    "w = tf.Variable(0.0, dtype=tf.float32, name=\"w\")\n",
    "b = tf.Variable(0.0, dtype=tf.float32, name=\"b\")\n",
    "\n",
    "pred = w * x + b\n",
    "\n",
    "loss_function = tf.reduce_mean(tf.square(y - pred))\n",
    "\n",
    "optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=0.1).minimize(loss_function)\n",
    "\n",
    "sess.run(tf.compat.v1.global_variables_initializer())\n",
    "\n",
    "x_data = np.linspace(-1, 1, 100)\n",
    "y_data = 3 * x_data + np.random.randn(*x_data.shape) * 0.3\n",
    "for step in range(1000):\n",
    "    sess.run(optimizer, feed_dict={x: x_data, y: y_data})\n",
    "\n",
    "x_new = np.random.normal(loc=0, scale=1, size=(1,)) \n",
    "print(\"x_new:\", x_new)\n",
    "\n",
    "print(\"目标值: %f\" % target)\n",
    "\n",
    "predict = sess.run(pred, feed_dict={x: x_new})\n",
    "print(\"预测值: %f\" % predict)\n",
    "\n",
    "print(\"预测值与真实值的绝对误差:\", abs(target - predict))\n",
    "\n",
    "sess.close()\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "tensorflow",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.20"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
